/** @format */

const fs = require("fs");
const { promisify } = require("util");
const rename = promisify(fs.rename);
const { Daily } = require("../model/index");
/**
 * @format
 * @param {Request} req
 * @param {Response} res
 */
module.exports.dailyUpload = async (req, res, next) => {
  const fileName = new TextDecoder("utf-16").decode(new Uint16Array(JSON.parse(req.file.originalname)).buffer);
  const fileArr = fileName.split(".xlsx");
  const name = fileArr[0] + "-" + Date.now() + ".xlsx";
  const dailyModel = new Daily({ time: Date.now(), url: name });
  try {
    await rename("./public/daily/" + req.file.filename, "./public/daily/" + name);
    await dailyModel.save();
    res.header("Access-Control-Allow-Origin", "*");
    res.status(201).json({ error: 0, data: { url: name } });
  } catch (err) {
    res.status(500).json({ error: 1, message: err });
  }
};
module.exports.excelUpload = async (req, res, next) => {
  const fileArr = req.file.originalname.split(".");
  const fileType = fileArr[fileArr.length - 1];
  try {
    await rename("./public/excel/" + req.file.filename, "./public/excel/" + Date.now() + "." + fileType);
    res.status(201).json({ error: 0, data: { url: Date.now() + "." + fileType } });
  } catch (err) {
    res.status(500).json({ error: 1, message: err });
  }
};
module.exports.upload = async (req, res, next) => {
  const fileArr = req.file.originalname.split(".");
  const fileType = fileArr[fileArr.length - 1];

  try {
    await rename("./public/" + req.file.filename, "./public/" + req.file.filename + "." + fileType);
    res.status(201).json({ error: 0, data: { url: req.file.filename + "." + fileType } });
  } catch (err) {
    res.status(500).json({ error: 1, message: err });
  }
};
